import os
import time
import allure
import pytest
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from loguru import logger
# from common.mylog import GeneralLogger
from common.readconfig import ReadConfig
from config.config import base_path
import pytest_check as pycheck


jpg_path = base_path + ReadConfig.parse_yaml(filename='config/webconfig.yaml', key='path.jpg')
if not os.path.exists(jpg_path):
    os.mkdir(jpg_path)

# logger=GeneralLogger().returnlogger()
# logger.add(log_path + now + '_all.log', rotation="00:00", encoding='utf-8')


class WebBase():
    def __init__(self, driver):
        self.driver = driver
        self.timeout = 10

    # 打开页面
    def openpage(self, url=''):
        if url == '':
            logger.error(f"url不能为空")
            raise
        else:
            with allure.step(f"打开'{url}'"):
                self.driver.get(url)
                logger.debug(f"打开'{url}'")

    # 查找元素
    def findElement(self, locator='', pagename='', elename='', doc='查找元素'):
        with allure.step(f"页面--{pagename}:{doc}'{elename}',定位方法'{locator[0]}',value值'{locator[1]}'"):
            if not isinstance(locator, tuple):
                logger.error(f"页面--{pagename}:{doc}'{elename}'，locator类型错误，必须传入元组类型，locator=（‘定位方法’，‘值’）")
                raise
            else:
                try:
                    element = WebDriverWait(self.driver, self.timeout).until(EC.presence_of_element_located(locator))
                    logger.debug(f"页面--{pagename}:{doc}'{elename}'成功,定位方法'{locator[0]}',value值'{locator[1]}'")
                    return element
                except Exception as e:
                    logger.error(f"页面--{pagename}:{doc}'{elename}'失败,定位方法'{locator[0]}',value值'{locator[1]}'")
                    return None

    # 查找元素
    # def findElements(self, locator):
    #     if not isinstance(locator, tuple):
    #         print('locator 类型错误，必须传入元组类型，locator=（“定位方法”，“值”）')
    #     else:
    #         try:
    #
    #             print('正在定位元素，定位方法' + locator[0] + ',value值' + locator[1])
    #             elements = WebDriverWait(self.driver, self.timeout).until(ec.presence_of_element_located(locator))
    #             return elements
    #         except:
    #             print('定位元素失败，定位方法' + locator[0] + ',value值' + locator[1])
    #             return []

    # 点击元素
    def click(self, locator='', pagename='', elename='', doc='点击元素'):
        element = self.findElement(locator=locator, pagename=pagename, elename=elename)
        with allure.step(f"页面--{pagename}:{doc}'{elename}',定位方法'{locator[0]}',value值'{locator[1]}'"):
            element.click()
        logger.debug(f"页面--{pagename}:{doc}'{elename}',定位方法'{locator[0]}',value值'{locator[1]}'")

    # 清空文本框
    def clear(self, locator='', pagename='', elename='', doc='清空文本框'):
        element = self.findElement(locator=locator, pagename=pagename, elename=elename)
        with allure.step(f"页面--{pagename}:{doc}'{elename}',定位方法'{locator[0]}',value值'{locator[1]}'"):
            element.clear()
            logger.debug(f"页面--{pagename}:{doc}'{elename}',定位方法'{locator[0]}',value值'{locator[1]}'")

    # 输入数据
    def sendkey(self, locator='', text='', pagename='', elename='', doc='输入数据'):
        element = self.findElement(locator=locator, pagename=pagename, elename=elename)
        with allure.step(f"页面--{pagename}:{doc}'{elename}',输入'{text}',定位方法'{locator[0]}',value值'{locator[1]}'"):
            element.send_keys(text)
            logger.debug(f"页面--{pagename}:{doc}'{elename}',输入'{text}',定位方法'{locator[0]}',value值'{locator[1]}'")

    # 切换iframe
    def switchiframe(self, iframe='', pagename='', iframename='', doc='切换iframe'):
        with allure.step(f"页面--{pagename}:{doc}'，{iframename},对应ID为{iframe}"):
            try:
                if isinstance(iframe, int):
                    self.driver.switch_to.frame(iframe)
                elif isinstance(iframe, str):
                    self.driver.switch_to.frame(iframe)
                logger.debug(f"页面--{pagename}:{doc}'，{iframename},对应ID为{iframe}")
            except Exception as e:
                logger.error(f"页面--{pagename}:{doc}'，{iframename}失败,对应ID为{iframe}")
                logger.error(e)
                raise e

    # 判断文本值
    def istext(self, locator, check='', pagename='', doc='判断文本值'):
        t = self.findElement(locator=locator, pagename=pagename, elename=check).text
        with allure.step(f"页面--{pagename}:{doc},获取值为:'{t}',期望值为'{check}'"):
            logger.info(f"页面--{pagename}:{doc},获取值为:'{t}',期望值为'{check}'")
            return pycheck.equal(t,check,'文本值检查不一致')
            # if t == check:
            #     logger.success(f"页面--{pagename}:{doc},获取值为:'{t}',期望值为'{check}'")
            #     return True
            # else:
            #     logger.warning(f"页面--{pagename}:{doc},获取值为:'{t}',期望值为'{check}'")
            #     return False


    # 判断title
    def istitle(self, check='', pagename='', doc='title检查'):
        with allure.step(f"页面--{pagename}:{doc}，获取titile为：{self.driver.title},期望title为:{check}"):
            try:
                result = WebDriverWait(self.driver, self.timeout).until(EC.title_is(check))
                logger.success(f"页面--{pagename}:{doc},获取titile为：{self.driver.title},期望title为:{check}")
                return result
            except:
                logger.warning(f"页面--{pagename}:{doc},获取titile为：{self.driver.title},期望title为:{check}")
                return False

    # 判断url
    def url_matches(self, check='', pagename="", doc="url路径检查"):
        try:
            result = WebDriverWait(self.driver, self.timeout).until(EC.url_matches(check))
            with allure.step(f"页面--{pagename}:{doc}"):
                logger.success(f"页面--{pagename}:{doc},获取url为:{self.driver.current_url}, 匹配url为:{check}")
                return result
        except:
            with allure.step(f"页面--{pagename}:{doc}，出错"):
                logger.warning(f"页面--{pagename}:{doc},出错")
                return False

    # 判断是否出现告警框
    def isAlertPersent(self, pagename="", doc='判断是否出现告警弹框'):
        with allure.step(f"页面--{pagename}:{doc}"):
            logger.debug(f"页面--{pagename}:{doc}")
            try:
                result = WebDriverWait(self.driver, self.timeout).until(EC.alert_is_present())
                return result
            except:
                return False

    # 告警框确认
    def alertaccept(self, pagename="", doc='点击告警框确认'):
        with allure.step(f"页面--{pagename}:{doc}"):
            if self.isAlertPersent(pagename=pagename):
                logger.debug(f"页面--{pagename}:{doc}")
                self.driver.switch_to.alert.accept()
            else:
                pass

    def save_myscreenshot(self, pagename=""):
        image_name = jpg_path + f"{pagename}_{time.strftime('%Y-%m-%d_%H_%M_%S', time.localtime())}.jpg"
        try:
            WebDriverWait(self.driver, 3).until(EC.alert_is_present())
            self.driver.switch_to.alert.accept()
            self.driver.save_screenshot(image_name)
            with open(image_name, mode='rb') as f:
                file = f.read()
            allure.attach(file, image_name, allure.attachment_type.JPG)
            logger.debug(f"页面:'{pagename}'截图成功, 文件名:{image_name}")
        except Exception as e:
            self.driver.save_screenshot(image_name)
            with open(image_name, mode='rb') as f:
                file = f.read()
            allure.attach(file, image_name, allure.attachment_type.JPG)
            logger.debug(f"页面:'{pagename}'截图成功, 文件名:{image_name}")

    # 获取文本
    def get_text(self, locator):
        try:
            t = self.findElement(locator)
            return t.text
        except:
            print('获取text失败，返回“”')
            return ""

        # 页面刷新

    def refresh(self):
        self.driver.refresh()

    def get_title(self):
        return self.driver.title

    def logout(self):
        self.driver.delete_all_cookies()
        self.driver.refresh()
